package com.junsi.app.common.exception;

import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.shiro.ShiroException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import com.junsi.app.common.page.ResultData;

/**
 * <p>File：GloablExceptionHandler.java</p>
 * <p>Title: </p>
 * <p>Description:</p>
 * <p>Copyright: Copyright (c) 2018 2018年11月29日 下午6:34:26</p>
 * <p>Company:  </p>
 * @author zmr
 * @version 1.0
 */
@ControllerAdvice
public class GloablExceptionHandler
{
	private Logger logger = LoggerFactory.getLogger(this.getClass());

    @ResponseBody
    @ExceptionHandler(Exception.class)
    public ResultData handleException(Exception e)
    {
		// 记录错误信息
		logger.error(ExceptionUtils.getFullStackTrace(e));
        String msg = e.getMessage();
        if (msg == null || msg.equals(""))
        {
            msg = "服务器出错";
        }

        return new ResultData(500, msg);
    }

	@ResponseBody
	@ExceptionHandler(BindException.class)
	public ResultData bindhHandleException(BindException e)
	{
		// 记录错误信息
		logger.error(ExceptionUtils.getFullStackTrace(e));
		String msg = e.getMessage();
		String message = "";
		if (msg == null || msg.equals(""))
		{
			message = "服务器出错";
		}

		for(ObjectError error:e.getBindingResult().getAllErrors()){
			message =error.getDefaultMessage();
		}
		return new ResultData(1000001, message);
	}

    // 捕捉UnauthorizedException
    @ResponseBody
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    @ExceptionHandler(UnauthorizedException.class)
    public ResultData handle401(UnauthorizedException e)
    {
        return new ResultData(401, e.getMessage());
    }

    // 捕捉shiro的异常
    @ResponseBody
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    @ExceptionHandler(ShiroException.class)
    public ResultData handle401(ShiroException e)
    {
        return new ResultData(401, "authorized error");
    }
}